package com.solution.wx.my.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.solution.admin.auth.entity.TodoEntity;
import com.solution.admin.coupon.constants.CouponConstants.IsUsed;
import com.solution.admin.coupon.entity.CouponGetEntity;
import com.solution.admin.coupon.service.CouponGetService;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.home.service.IndexService;
import com.solution.admin.home.service.RedisService;
import com.solution.admin.point.constants.PointConstants.PointOperateType;
import com.solution.admin.point.entity.PointEntity;
import com.solution.admin.point.entity.PointLogEntity;
import com.solution.admin.point.entity.SignPointSettingsEntity;
import com.solution.admin.point.service.PointLogService;
import com.solution.admin.point.service.PointService;
import com.solution.admin.point.service.SignPointSettingsService;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.config.PublicConfig;
import com.solution.common.config.PublicConfigUtil;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.QrcodeUtil;
import com.solution.common.utils.RandomUtils;
import com.solution.common.utils.ip.IPUtils;
import com.solution.common.utils.sms.AliyunSmsUtils;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.home.constants.HomeConstants.SmsTemplateType;
import com.solution.wx.common.constants.PublicConstants;
import com.solution.wx.core.constants.WechatConstants;
import com.solution.wx.core.entity.SNSUserEntity;
import com.solution.wx.core.util.WechatUtil;
import com.solution.wx.my.constants.MyConstants;
import com.solution.wx.share.entity.ShareInfoEntity;
import com.solution.wx.share.service.ShareInfoService;

/**
 * 客户个人中心控制层
 * 
 * @author: solin
 * @date: 2017年11月17日 上午11:53:53
 */
@RequestMapping("/wx/my")
@Controller("wxMyController")
public class MyController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(MyController.class);
	@Autowired
	RedisService redisService;
	@Autowired
	PointService pointService;

	@Autowired
	PointLogService pointLogService;

	@Autowired
	SignPointSettingsService signPointSettingsService;

	@Autowired
	CouponGetService couponGetService;
	
	@Autowired
	IndexService indexService;
	
	@Autowired
	private KeyMapService keyMapService;
	
	@Autowired
	private ShareInfoService shareInfoService;

	/**
	 * 跳转到个人中心页面
	 * 
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月17日 上午11:53:36
	 */
	@RequestMapping("")
	public String toMyPage(HttpServletRequest request) {
		try {
			request.setAttribute(PublicConstants.CURRENT_PAGE_KEY, PublicConstants.PAGE_MY);
			// 从cookie中获取openId
			String openId = WechatUtil.getOpenIdFromCookie(request);
			// 从redis中获取通过网页授权获取的用户信息
			String strSNSUserInfoJson = redisService.get(WechatConstants.SNS_USERINFO_KEY.concat(openId));
			SNSUserEntity snsUserInfo = JSONObject.parseObject(strSNSUserInfoJson, SNSUserEntity.class);
			// 获取客户信息
			CustomerEntity customerInfo = this.getCustomer();
			String headImageUrl = "";
			if (StringUtil.isNotEmpty(customerInfo.getHeadImage())) {
				headImageUrl = customerInfo.getHeadImage();
			} else {
				headImageUrl = PublicConfig.IMG_ROOT_URL.concat(customerInfo.getHeadImage());
			}
			request.setAttribute("headImageUrl", headImageUrl);
			request.setAttribute("customerInfo", customerInfo);

			/** add by xu_cc [积分、签到相关] 2017.11.21 begin */
			// 积分
			Long customerId = getCustomerId();
			if (null != customerId) {
				PointEntity pointObj = pointService.getPointByCustomerId(customerId);
				BigDecimal point = (null != pointObj) ? pointObj.getPoint() : BigDecimal.ZERO;
				request.setAttribute("point", point);
			}
			// 今天生效的签到积分规则
			String pattern = "yyyy-MM-dd";
			String currentDateStr = DateFormatUtils.format(new Date(), pattern);
			// 查看今天是否有签到积分设置信息
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("startTime", currentDateStr);
			paramMap.put("endTime", currentDateStr);
			// 查看是否有时间冲突的记录
			BigDecimal signPoint = BigDecimal.ZERO;
			List<SignPointSettingsEntity> signPointSettingsList = signPointSettingsService.listSignPointSettings(paramMap);
			if (null != signPointSettingsList && signPointSettingsList.size() > 0) {
				// 获取设置的积分
				signPoint = signPointSettingsList.get(0).getSignPoint();
			} else {
				// 取不到签到积分规则，那就取默认签到赠送积分
				String signPointStr = PublicConfigUtil.readConfig("sign.default.point");
				if (StringUtil.isNotNull(signPointStr)) {
					signPoint = new BigDecimal(signPointStr);
				}
			}
			request.setAttribute("signPoint", signPoint);
			// 今天是否已经签到
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("customerId", customerId);
			param.put("operateType", PointOperateType.OPT_SIGN.getCode());
			param.put("today", 1);// today只要有值就行，不限制
			List<PointLogEntity> signLogList = pointLogService.listPointLog(param);
			if (null != signLogList && signLogList.size() > 0) {
				request.setAttribute("isSigned", 1);
			} else {
				request.setAttribute("isSigned", 0);
			}
			/** add by xu_cc [积分、签到相关] 2017.11.21 end */
			
			// 查询待办事项数量
			Map<String, Object> tparam = new HashMap<>();
			tparam.put("customerId", getCustomerId());
			List<TodoEntity> todoList =  indexService.listWXTodoList(tparam);
			if(todoList != null && todoList.size() > 0){
			for (TodoEntity todo : todoList) {
					request.setAttribute(todo.getTodoName(), todo.getTodoNum());
				}
			}
			
			//签到控制,是否允许签到 1 允许,其他 禁止
			List<KeyMapEntity> signInControlList = keyMapService.listKeyMap("signInControl");
			if (null != signInControlList && signInControlList.size() != 0) {
				KeyMapEntity signInControl = signInControlList.get(0);
				if ("1".equals(signInControl.getKeyValue())) {
					request.setAttribute("signInControl", signInControl.getKeyValue());
				} else {
					request.setAttribute("signInControl", "0");
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "wx/my/my";
	}

	/**
	 * 转优惠券页面
	 * 
	 * @param request
	 * @return String
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月21日 上午11:34:39
	 */
	@RequestMapping("/toCouponPage")
	public String toWxCouponPage(HttpServletRequest request, Model model) {
		try {
			/* 未使用优惠券 */
			List<CouponGetEntity> couponGetList = new ArrayList<CouponGetEntity>();
			/* 过期优惠券 */
			List<CouponGetEntity> couponExpList = new ArrayList<CouponGetEntity>();
			/* 过期优惠券 */
			List<CouponGetEntity> couponUsedList = null;

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("customerId", getCustomerId());
			// 用户所有领取的优惠券
			List<CouponGetEntity> getAllCouponList = couponGetService.listCouponGet(param);
			if (null != getAllCouponList && getAllCouponList.size() > 0) {
				Date currentDate = new Date();
				for (CouponGetEntity couponGet : getAllCouponList) {
					if (null == couponGet || IsUsed.USED.equals(couponGet.getIsUsed())) {
						continue;
					}
					if (IsUsed.UN_USED.equals(couponGet.getIsUsed())) {
						if (currentDate.after(couponGet.getEndTime())) {
							// 已过期
							couponExpList.add(couponGet);
						} else if (currentDate.before(couponGet.getEndTime())) {
							// 未使用
							couponGetList.add(couponGet);
						}
					}
				}
			}
			// 已用优惠券
			param.put("isUsed", IsUsed.USED);
			couponUsedList = couponGetService.listCouponGet(param);
			// 个数
			model.addAttribute("couponGetCount", couponGetList.size());
			model.addAttribute("couponExpCount", couponExpList.size());
			model.addAttribute("couponUsedCount", (null != couponUsedList ? couponUsedList.size() : 0));
			// 集合
			model.addAttribute("couponGetList", couponGetList);
			model.addAttribute("couponExpList", couponExpList);
			model.addAttribute("couponUsedList", couponUsedList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "wx/my/coupon/coupon";
	}

	/**
	 * 发送手机验证码
	 * 
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月16日 上午11:28:41
	 */
	@RequestMapping("/sendVerifyCode")
	@ResponseBody
	public Map<String, Object> sendVerifyCode(HttpServletRequest request, String mobile) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			//发送短信
			sendShortMsg(request, mobile);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "短信验证码发送成功！");
		} catch (Exception e) {
			logger.error("短信验证码发送失败:{}", e);
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "短信验证码发送失败,请稍候再试！");
		}

		return resultMap;
	}
	
	/**
	 * 发送短信验证码
	 * @param request
	 * @param mobile
	 * @return
	 * @author: solin
	 * @date: 2017年12月25日 下午7:11:03
	 */
	private boolean sendShortMsg(HttpServletRequest request, String mobile) {
		boolean sendStatus = false;
		// redis中的验证码KEY
		String verifyCodeKey = MyConstants.MOBILE_VERIFY_CODE_KEY.concat(IPUtils.getIntenetIP(request));
		// 发送短信
//		String templateId = "SMS_126866486";
		String verifyCode = RandomUtils.getRandNum(6);
		// 保存到redis
		redisService.save(verifyCodeKey, verifyCode, (30 * 60));
		System.out.println("============>>>短信验证码:" + verifyCode);
		String params = "{\"code\":\"" + verifyCode + "\"}";
		sendStatus = AliyunSmsUtils.sendSms(SmsTemplateType.SMS_VALID.getTemplateId(), mobile, params);
		return sendStatus;
	}
	
	/**
	 * 我的分享
	 * @param request
	 * @param response
	 * @return String
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年5月16日 下午5:00:19
	 */
	@RequestMapping("/myShare")
	public String listMyShareInfoPage(HttpServletRequest request, HttpServletResponse response) {
		PageParam pageParam = getPageParam(request);
		// pageParam.setNumPerPage(6);
		String searchKey = request.getParameter("searchKey");
		String requestType = request.getParameter("requestType");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("searchKey", searchKey);
		List<String> orderByList = new ArrayList<String>();
		if (StringUtil.isNotNull(request.getParameter("likeSort"))) {
			orderByList.add("likeQuantity "+request.getParameter("likeSort"));
			request.setAttribute("likeSort", request.getParameter("likeSort"));
		}
		if (StringUtil.isNotNull(request.getParameter("commentSort"))) {
			orderByList.add("commentQuantity "+request.getParameter("commentSort"));
			request.setAttribute("commentSort", request.getParameter("commentSort"));
		}
		if (StringUtil.isNotNull(request.getParameter("favoriteSort"))) {
			orderByList.add("favoriteQuantity "+request.getParameter("favoriteSort"));
			request.setAttribute("favoriteSort", request.getParameter("favoriteSort"));
		}
		param.put("orderByList", orderByList);

		// 获取openId
		String openId = WechatUtil.getOpenIdFromCookie(request);
		param.put("wxOpenId", openId);
		// 客户ID
		CustomerEntity customer = getCustomer();
		if (null != customer) {
			param.put("shareUserId", customer.getId());
		}
		try {
			PageBean shareInfoPage = shareInfoService.listMySharePage(pageParam, param);
			// 检查用户是否对该分析内容点赞
			for (int i = 0; i < shareInfoPage.getRecordList().size(); i++) {
				ShareInfoEntity shareInfoEntity = (ShareInfoEntity) shareInfoPage.getRecordList().get(i);
				Integer isUserLike = shareInfoService.isUserLike(shareInfoEntity.getId(), getCustomerId()) > 0 ? 1 : 0;
				shareInfoEntity.setIsUserLike(isUserLike);
			}
			// 如果是异步，直接写response
			if ("sync".equals(requestType)) {
				try {
					response.getWriter().write(JSONObject.toJSON(shareInfoPage).toString());
					response.getWriter().flush();
					response.getWriter().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			request.setAttribute("pageBean", shareInfoPage);
			request.setAttribute("requestType", requestType);
			request.setAttribute("searchKey", searchKey);
		} catch (Exception e) {
			handleException("查询分享信息失败", logger, e);
		}
		return "wx/my/share/my_share_list";
	}

	/**
	 * 我的推广码页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return String
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年5月16日 下午3:14:10
	 */
	@RequestMapping("/myInvitation")
	public String toMyInvitationCodePage(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			CustomerEntity customer = getCustomer();
			if (null == customer) {
				// 去登录
				return "redirect:/wx/my/toBindAccountPage";
			} else {
				// 邀请码获取
				String incitationCode = customer.getInvitationCode();
				if (StringUtil.isEmpty(incitationCode)) {
					// 邀请码为空，则自动生成，五位数字，id结尾生成的
					incitationCode = String.format("%0" + 5 + "d", customer.getId());
				}
				model.addAttribute("incitationCode", incitationCode);
				
//				String imageBase64QRCode = QrcodeUtil.encodeToBase64(url, logoImage, false);
//				System.out.println("新二维码路径：" + imageBase64QRCode);
				
				// 二维码生成base64字符串图片
//				System.out.println("OLD:" + ZXQrCodeUtils.getLogoQRCode(url, "景旭分销在线欢迎你"));
//				model.addAttribute("imageBase64QRCode", imageBase64QRCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "wx/my/share/invitation";
	}

	/**
	 * 图片验证码生成
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 *             void
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年9月20日 下午7:21:02
	 */
	@RequestMapping("/invitationCode.jpg")
	public void invitationCodeImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			// 通知浏览器不要缓存
			response.setHeader("Expires", "-1");
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Pragma", "-1");
			// 邀请码获取
			CustomerEntity customer = getCustomer();
			String incitationCode = customer.getInvitationCode();
			if (StringUtil.isEmpty(incitationCode)) {
				// 邀请码为空，则自动生成，五位数字，id结尾生成的
				incitationCode = String.format("%0" + 5 + "d", customer.getId());
			}
			// 二维码生成
			// LOGO 路径
			String logoImage = request.getSession().getServletContext().getRealPath("/").concat("statics" + File.separator + "images" + File.separator + "jx.ico");
			System.out.println("LOGO路径：" + logoImage);
			String url = request.getScheme() + "://" + request.getServerName() + "/wx/my/toRegisterPage?invitationCode=" + incitationCode;
			System.out.println(customer.getUserName() + "二维码路径：" + url);
//			try {
//				String osName = System.getProperty("os.name").toLowerCase();
//				if (null != osName && osName.contains("win")) {
//					ImageIO.write(util.getImage(), "jpg", new File("c:/" + code + ".jpg"));
//				} else {
//					ImageIO.write(util.getImage(), "jpg", new File("/usr/" + code + ".jpg"));
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			// 输出打web页面
			BufferedImage image = QrcodeUtil.encodeImg(url, logoImage, false);
			ImageIO.write(image, "jpg", response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
